#encoding:utf8 

from framework.db import IncDB
from handlers.configs import *

class userData():
	@staticmethod
	def new():
		data = dict(
			lv = 1,
			exp = 0,
			money = 0,
			diamond = 0,
			name = 0,
			items = []
			)
		return data 

	@staticmethod 
	def find_by_uid(uid):
		ret = None 
		ret = IncDB.findOnce("userdata" , {"_id":uid})
		return ret 

	@staticmethod 
	def insert_user(uid , user):
		user["_id"] = uid
		ret = IncDB.insertOnce("userdata" , user)
		return ret 

	@staticmethod
	def _update(uid , updatedic):
		IncDB.updateV("userdata" , {"_id":uid} , {"$set":updatedic})

	@staticmethod
	def add_money(data , money):
		data["money"] = data["money"] + money
		#record
		userData._update(data["_id"] , {"money":data["money"]})
		return 0

	@staticmethod
	def cost_money(data , money):
		ret = 0 and data["money"] > money or 1 
		if ret == 0:
			data["money"] = data["money"] - money
			#record
			userData._update(data["_id"] , {"money":data["money"]})
		return ret 

	@staticmethod	
	def add_exp(data , exp):
		maxlv = len(ConfigLv.LV) - 1
		maxexp = ConfigLv.LV[lmaplv]

		nowlv = data["lv"]

		data["exp"] = data["exp"] + exp
		if data["exp"] > maxexp:
			data["exp"] = maxexp
		
		if nowlv + 1 <= maxlv:
			if data["exp"] >= ConfigLv[nowlv + 1]:
				for i in range(nowlv , maxlv):
					if data["exp"] >= ConfigLv.LV[i]:
						data["lv"] = i
					else:
						break

		if nowlv != data["lv"]:
			userData._update(data["_id"] , {"exp":data["exp"] ,"lv":data["lv"]})	
		userData._update(data["_id"] , {"exp":data["exp"]})	

		data["lv"] = nowlv
		return 0

